import axios from "axios";
import router from "../router";

const http = axios.create({
    baseURL : import.meta.env.VITE_API_URL
})

// 添加请求拦截器
http.interceptors.request.use(function (config:any) {
// 在发送请求之前做些什么
    if(config.url !== 'Login'){
        let token = sessionStorage.getItem('token')
        if(!token){
            router.push({path:'/'})
        }else{
            if(!sessionStorage.getItem('token')){
                sessionStorage.setItem('token',token)
            }
        }
        config.headers['Authorization'] = 'Bearer ' + token
        config.headers['content-type'] = 'application/x-www-form-urlencoded'
        let project:any = sessionStorage.getItem('project')
        if(project){
            project = project ? JSON.parse(project) : '';
            if(config.method != 'delete' && config.method != 'get'){
                if(!config.data['project_id']){
                    config.data['project_id'] = project.id
                }
            }else{
                config.headers['project_id'] = project.id
            }
        }

    }
    return config;
}, function (error) {
// 对请求错误做些什么
    console.log(error)
    return Promise.reject(error);
});


// 添加响应拦截器
http.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    
    if(response.data.code == 401){
        router.push({path:'/'})
    }

    return response;
  }, function (error) {
    if(error.status == 401){
        router.push({path:'/'})
    }
    // 对响应错误做点什么
    return Promise.reject(error);
  });

export default http
